import React from 'react';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Card, message} from 'antd';
import {FORM_OPTIONS, FORM_ROW_OPTIONS} from '../constants';
import {PERMISSION} from './constants';
import {salePlanOrderStatus} from '../Enum';
import WrappedSelect from '../common/WrappedSelect';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import ManufacturerSelectPanel from './ManufacturerSelectPanel';
import MarketDepartmentSelectPanel from './MarketDepartmentSelectPanel';
import SearchSelectPanel from '../common/DutyUnitSelect/SelectEdit';
import TextInput from 'Shared/components/TextInput';
import WrappedInputNumber from '../common/WrappedInputNumber';
import TagSelect from 'Shared/components/TagSelect';
import Export from '../common/Export';
import {hasPermissions} from './utils';
import {injectIntl, language} from './intl';
import BatchImportPanel from './ImportPanel';
import routes from './routes';
import {getMarketDepartment, getMarketDepartmentSimple, getManufacturerSimple, getManufacturer} from './api';
const FormItem = Form.Item;

class QueryPanel extends React.PureComponent {
    state = {
        data: {
            manufacturerName: '',
            marketDepartmentName: '',
        },
        showBatchImport: false,
        showManufacturerSelectPanel: false,
        showMarketDepartmentSelectPanel: false,
    }
    handleFilterChange = (value, name) => {
        this.props.onConditionsChange(name, value);
    }
    handleFilterPressEnter = (value, name) => {
        this.props.onConditionsChange(name, value);
        this.props.querySearch();
    }
    query = () => {
        if(!this.props.conditions.submitYear || !this.props.conditions.submitMonth)
            return message.warn(this.props.intl.formatMessage({
                id: 'queryPanel.query.message',
                defaultMessage: '查询条件提报年份和月份不能为空'
            }));
        this.props.querySearch();
    }
    batchImportChange = data => {
        if(data) {
            this.setState({showBatchImport: false});
            message.success(this.props.intl.formatMessage({
                id: 'queryPanel.msg.batchImport',
                defaultMessage: '批量导入成功'
            }));
            this.props.querySearch();
        }
    }
    reset = () => {
        this.setState({
            data: {
                manufacturerName: '',
                marketDepartmentName: '',
            },
        });
        this.props.onResetClick();
    }
    handleFilterSubmit = () => {
        this.props.onConditionsChange('status', [salePlanOrderStatus.新建, salePlanOrderStatus.已驳回]);
        this.props.querySearch();
        this.props.onClickSubmitBtn();
    }
    handleFilterAbandon = () => {
        this.props.onConditionsChange('status', [salePlanOrderStatus.新建, salePlanOrderStatus.已驳回]);
        this.props.querySearch();
        this.props.onClickAbandonBtn();
    }
    handleFilterApprove = () => {
        this.props.onConditionsChange('status', [salePlanOrderStatus.已提交, salePlanOrderStatus.审核中]);
        this.props.querySearch();
        this.props.onClickApproveBtn();
    }
    onSelectDealer = data => {
        this.handleFilterChange(data.id, 'dealerId');
        this.props.onSelect({
            id: data.id,
            code: data.code,
            name: data.name,
        });
    }
    onSelectManufacturer = records => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                manufacturerId: records.id,
                manufacturerName: records.name,
            }),
            hasOperat: true,
            showManufacturerSelectPanel: false
        });
        this.props.onConditionsChange('manufacturerId', records.id);
    }
    onSelectMarketDepartment = records => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                marketDepartmentId: records.id,
                marketDepartmentName: records.name,
            }),
            hasOperat: true,
            showMarketDepartmentSelectPanel: false
        });
        this.props.onConditionsChange('marketDepartmentId', records.id);
    }
    onBatchImport = () => this.setState({showBatchImport: true});
    onCloseBatchImport = () => this.setState({showBatchImport: false});
    onClickSearchManufacturerBtn = () => this.setState({showManufacturerSelectPanel: true});
    onCloseManufacturerSelectPanel = () => this.setState({showManufacturerSelectPanel: false});
    onClickSearchMarketDepartmentBtn = () => this.setState({showMarketDepartmentSelectPanel: true});
    onCloseMarketDepartmentSelectPanel = () => this.setState({showMarketDepartmentSelectPanel: false});
    render() {
        const {formatMessage} = this.props.intl;
        const {brands} = this.props.initEnumData;
        const otherOperations = [];
        const {conditions, queryDealer, permissions, addable,
            querySearch, loading, exportable, onClickExport,
            isShowBatchAbandonPanel, isShowBatchApprovePanel,
            isShowBatchSubmitPanel} = this.props;
        const dealerInfo = conditions.dealerId ? {
            id: queryDealer.id,
            code: queryDealer.code,
            name: queryDealer.name
        } : null;
        const markeInfo = conditions.marketDepartmentId ? {
            id: conditions.marketDepartmentId,
            name: conditions.marketDepartmentName
        } : null;
        const manufacturerInfo = conditions.manufacturerId ? {
            id: conditions.manufacturerId,
            name: conditions.manufacturerName
        } : null;
        if(hasPermissions(permissions, PERMISSION.submit))
            otherOperations.push(<Button key="submit" onClick={this.handleFilterSubmit}>{formatMessage({
                id: 'queryPanel.btn.submit',
                defaultMessage: '批量提交'
            })}</Button>);
        if(hasPermissions(permissions, PERMISSION.approve))
            otherOperations.push(<Button key="approve" onClick={this.handleFilterApprove}>{formatMessage({
                id: 'queryPanel.btn.approve',
                defaultMessage: '批量审核'
            })}</Button>);
        if(hasPermissions(permissions, PERMISSION.abandon))
            otherOperations.push(<Button key="abandon" onClick={this.handleFilterAbandon}>{formatMessage({
                id: 'queryPanel.btn.abandon',
                defaultMessage: '批量作废'
            })}</Button>);
        return (
            <div>
                <Form className="form-standard">
                    <Card>
                        <Row>
                            {brands.length !== 1 && <Col {...FORM_OPTIONS.col}><FormItem label={formatMessage({
                                id: 'queryPanel.form.brandId',
                                defaultMessage: '品牌'
                            })}{...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="brandId"
                                    value={conditions.brandId}
                                    options={brands}
                                    onChange={this.handleFilterChange}/>
                            </FormItem>
                            </Col>}
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={formatMessage({
                                        id: 'queryPanel.form.marketDepartmentId',
                                        defaultMessage: '大区'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <SearchSelectPanel
                                        value={markeInfo}
                                        getDutyUnits={getMarketDepartment}
                                        getDutyUnitSimple={getMarketDepartmentSimple}
                                        titleName={formatMessage({
                                            id: 'queryPanel.form.marketDepartmentId',
                                            defaultMessage: '大区'
                                        })}
                                        isLabelMap={false}
                                        onSelect={this.props.onSelectMarke} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={formatMessage({
                                        id: 'queryPanel.form.dealerId',
                                        defaultMessage: '总代'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <DealerSelectPanel
                                        value={dealerInfo}
                                        onSelect={this.onSelectDealer} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={formatMessage({
                                        id: 'queryPanel.form.planCode',
                                        defaultMessage: '计划编号'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <TextInput
                                        name="planCode"
                                        value={conditions.planCode}
                                        onPressEnter={this.handleFilterPressEnter}
                                        onBlur={this.handleFilterChange}/>
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={formatMessage({
                                        id: 'queryPanel.form.manufacturerId',
                                        defaultMessage: '生产工厂'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <SearchSelectPanel
                                        value={manufacturerInfo}
                                        getDutyUnits={getManufacturer}
                                        getDutyUnitSimple={getManufacturerSimple}
                                        titleName={formatMessage({
                                            id: 'queryPanel.form.manufacturerId',
                                            defaultMessage: '生产工厂'
                                        })}
                                        isLabelMap={false}
                                        onSelect={this.props.onSelectManufacturer} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={formatMessage({
                                        id: 'queryPanel.form.submitYear',
                                        defaultMessage: '提报年份'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <WrappedInputNumber
                                        min={0}
                                        precision={0}
                                        name="submitYear"
                                        value={conditions.submitYear}
                                        onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={formatMessage({
                                        id: 'queryPanel.form.submitMonth',
                                        defaultMessage: '提报月份'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <WrappedInputNumber
                                        name="submitMonth"
                                        value={conditions.submitMonth}
                                        onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col>
                                <FormItem label={formatMessage({
                                    id: 'queryPanel.form.status',
                                    defaultMessage: '状态'
                                })} {...FORM_ROW_OPTIONS.item}>
                                    <TagSelect
                                        name="status"
                                        value={conditions.status}
                                        options={salePlanOrderStatus.toList(language)}
                                        onChange={this.handleFilterChange} />
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={6}>
                                <Button key="query" type="primary" onClick={this.query} loading={loading}>{formatMessage({
                                    id: 'queryPanel.btn.query',
                                    defaultMessage: '查询'
                                })}</Button>
                                <Button key="clear" onClick={this.reset}>{formatMessage({
                                    id: 'queryPanel.btn.reset',
                                    defaultMessage: '重置'
                                })}</Button>
                            </Col>
                            <Col span={18} className="col-align-right">
                                <Button.Group>
                                    {(!isShowBatchSubmitPanel && !isShowBatchAbandonPanel &&
                                        !isShowBatchApprovePanel) && otherOperations}
                                    {(hasPermissions(permissions, PERMISSION.batchImport) &&
                                        <Button key="batchImport" onClick={this.onBatchImport}>{formatMessage({
                                            id: 'queryPanel.btn.batchImport',
                                            defaultMessage: '批量导入'
                                        })}</Button>)}
                                    {exportable && <Export key={PERMISSION.export} exportRequest={onClickExport} />}
                                </Button.Group>
                                {addable && <Button key="add" type="primary" href={`#${routes.add.url()}`}>{formatMessage({
                                    id: 'queryPanel.btn.add',
                                    defaultMessage: '新增'
                                })}</Button>}
                            </Col>
                        </Row>
                        {this.state.showBatchImport &&
                        <BatchImportPanel
                            selectKey="BatchImportPanel"
                            onCancel={this.onCloseBatchImport}
                            onImportChange={this.batchImportChange} />
                        }
                        {this.state.showManufacturerSelectPanel &&
                        <ManufacturerSelectPanel
                            onCancel={this.onCloseManufacturerSelectPanel}
                            onSelect={this.onSelectManufacturer} />}
                        {this.state.showMarketDepartmentSelectPanel &&
                        <MarketDepartmentSelectPanel
                            onCancel={this.onCloseMarketDepartmentSelectPanel}
                            onSelect={this.onSelectMarketDepartment} />}
                    </Card>
                </Form>
            </div>
        );
    }
}

QueryPanel.propTypes = {
    conditions: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    querySearch: PropTypes.func.isRequired,
    onClickAbandonBtn: PropTypes.func.isRequired,
    onClickApproveBtn: PropTypes.func.isRequired,
    onClickSubmitBtn: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onResetClick: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
    onSelectManufacturer: PropTypes.func.isRequired,
    onSelectMarke: PropTypes.func.isRequired,
    intl: PropTypes.object,
    isShowBatchAbandonPanel: PropTypes.bool,
    isShowBatchApprovePanel: PropTypes.bool,
    isShowBatchSubmitPanel: PropTypes.bool,
};

import {connect} from 'react-redux';
import {saveQueryCondition, querySearch, resetQueryPanel, saveQueryDealer,
    exportData, startBatchAbandon, startBatchSubmit, startBatchApprove,
    selectMarkeQuery, selectManufacturerQuery} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: item.name,
            value: item.id
        })) : [];
        return {
            brands
        };
    }
);
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const getQueryDealer = selectorFactory(['page', 'appState', 'queryDealer']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    conditions: getConditions(state),
    initEnumData: getinitEnumData(state),
    permissions: getPermissions(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    exportable: state.getIn(['page', 'domainData', 'permission', 'data']).includes(PERMISSION.export),
    addable: state.getIn(['page', 'domainData', 'permission', 'data']).includes(PERMISSION.add),
    queryDealer: getQueryDealer(state),
    isShowBatchAbandonPanel: state.getIn(['page', 'ui', 'showBatchAbandonPanel']),
    isShowBatchSubmitPanel: state.getIn(['page', 'ui', 'showBatchSubmitPanel']),
    isShowBatchApprovePanel: state.getIn(['page', 'ui', 'showBatchApprovePanel']),
});

const mapDispatchToProps = dispatch => ({
    onConditionsChange: (name, value) => dispatch(saveQueryCondition(name, value)),
    querySearch: () => dispatch(querySearch()),
    onResetClick: () => dispatch(resetQueryPanel()),
    onSelect: data => dispatch(saveQueryDealer(data)),
    onClickExport: () => dispatch(exportData()),
    onClickAbandonBtn: () => dispatch(startBatchAbandon()),
    onClickSubmitBtn: () => dispatch(startBatchSubmit()),
    onClickApproveBtn: () => dispatch(startBatchApprove()),
    onSelectMarke: data => dispatch(selectMarkeQuery(data)),
    onSelectManufacturer: data => dispatch(selectManufacturerQuery(data)),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(QueryPanel));
